package com.example.springbatchdemo.config.xml;

import com.example.springbatchdemo.config.file.Weather;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.xml.StaxEventItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.oxm.xstream.XStreamMarshaller;

import java.util.HashMap;
import java.util.Map;

/**
 * @Classname XmlItemDemo
 * @Description TODO
 * @Date 2020/9/22 22:15
 * @Created by kevin
 */
@Configuration
public class XmlItemDemo {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;
    @Autowired
    private StepBuilderFactory stepBuilderFactory;
    @Autowired
    private XmlFileWriter xmlFileWriter;

    @Bean
    public Job xmlItemDemoJob() {
        return jobBuilderFactory.get("xmlItemDemoJob")
                .start(xmlItemDemoStep())
                .build();
    }


    @Bean
    public Step xmlItemDemoStep() {
        return stepBuilderFactory.get("xmlItemDemoStep")
                .<Weather, Weather>chunk(2)
                .reader(xmlFileReader())
                .writer(xmlFileWriter)
                .build();
    }

    @Bean
    @StepScope
    public StaxEventItemReader<Weather> xmlFileReader() {
        StaxEventItemReader<Weather> reader = new StaxEventItemReader<>();
        // 指定读取文件的位置
        reader.setResource(new ClassPathResource("data.xml"));
        // 指定需要处理的跟标签
        reader.setFragmentRootElementName("weather");
        // 把读取的xml数据转化为对象
        XStreamMarshaller marshaller = new XStreamMarshaller();

        Map<String, Class> map = new HashMap<>();
        map.put("weather", Weather.class);
        // 指定转化类型
        marshaller.setAliases(map);
        reader.setUnmarshaller(marshaller);
        return reader;
    }

}
